//
//  HTTPClient.m
//  王雷Sinoweibo
//
//  Created by wanglei on 16/12/2.
//  Copyright © 2016年 wanglei. All rights reserved.
//

#import "HTTPClient.h"
static HTTPClient *tools = nil;
//定义反转域名
NSString *const domain = @"com.baidu.data.error";
@implementation HTTPClient

//设计单例
+(instancetype)sharedClient;{
    static dispatch_once_t oncetoken;
    dispatch_once(&oncetoken, ^{
        NSString *urldtr = @"https://api.weibo.com/";
        NSURL *url = [NSURL URLWithString:urldtr];
        tools = [[HTTPClient alloc]initWithBaseURL:url];
//        设置支持解析的数据类型
        tools.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/plain",@"text/json", @"text/javascript", nil];
    });
    
    return tools;
}

- (void)requestJSONDict:(HTTPMethods *)method urlstring:(NSString *)urlstring parameters:(id  _Nullable)parameters finished:(finished)isfinished;{
//  详细解释见  http://www.jianshu.com/p/e34f2162d2f3
    NSError *myerror = [[NSError alloc]initWithDomain:domain code:10000 userInfo:@{NSLocalizedDescriptionKey:@"数据结构解析出错"}];
    if (method == GET) {
        [self GET:urlstring parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSLog(@"%@",[responseObject class]);
            if(![responseObject isKindOfClass:[NSDictionary class]]){
                isfinished(nil,myerror);
                return ;
            }
            isfinished(responseObject,nil);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            isfinished(nil,error);
            NSLog(@"%@",error);
        }];
    }else{
        [self POST:urlstring parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            if(![responseObject isKindOfClass:[NSDictionary class]]){
                isfinished(nil,myerror);
                return ;
            }
            isfinished(responseObject,nil);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            isfinished(nil,error);
            NSLog(@"%@",error);
        }];
    }
}

@end
